package com.cn.removewatermark.parsingurl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.removewatermark.batchdownload.BatchDownload;
import com.cn.removewatermark.batchdownload.DownloadThead;
import com.cn.removewatermark.utils.FileUtils;
import com.cn.removewatermark.utils.UrlUtils;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.*;

/**
* 解析视频的url（单独下载某个视频）
 *      适合使用于手机app上分享的视频链接
* */
public class ParsingURLs {

    public  final static Properties properties;
    private  final  static HashMap<String ,String> heards=new HashMap<>();

    public static double progress =0;

    static {
        /*Path path = Paths.get("src/main/java","com/cn/removewatermark/client.properties");
        Path absolutePath = path.toAbsolutePath();*/
         properties=new Properties();
        InputStream in=null;
        try {
//            in=new FileInputStream(absolutePath.toString());
            in = ParsingURLs.class.getClassLoader().getResourceAsStream("com/cn/removewatermark/client.properties");
            properties.load(in);
            heards.put("User-Agent", (String) properties.get("User-Agent"));
            BatchDownload.header.put("User-Agent",(String) properties.get("Windows"));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (in!=null){
                    in.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    /*
    *解析快手的url
    * */
    public  void kuaiShouParsingUrl(String url) throws IOException {
        HttpResponse redirceResponse = HttpUtil.createGet(url).addHeaders(heards).execute();
        String redirUrl =  redirceResponse.header("Location");
        Map<String, String> map = UrlUtils.urlParamToMap(redirUrl.substring(redirUrl.indexOf("?")+1, redirUrl.length()));
        HttpResponse response = HttpUtil.createGet(redirUrl).addHeaders(heards).execute();
        String realAddress="https://v.m.chenzhongtech.com/rest/wd/photo/info?kpn="+map.get("kpn")+"&captchaToken=&__NS_sig3=";
        heards.put("Referer",redirUrl);
        HttpRequest request = HttpUtil.createPost(realAddress)
                .addHeaders(heards)
                .contentType("application/json")
                .cookie(response.getCookies());
        JSONObject obj=JSONUtil.createObj();
        obj.put("fid",map.get("fid"));
        obj.put("photoId",map.get("photoId"));
        request.body(obj.toString());
        HttpResponse execute = request.execute();
        JSONObject jsonObject = JSONUtil.parseObj(execute.body());
        String mp4Url =(String)jsonObject.get("mp4Url");
        download(mp4Url);
    }

    /*
    * 下载视频
    * */
    private void  download(String url){
        BufferedOutputStream bufferedOutputStream=null;
        try {
            bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(Paths.get(DownloadThead.path+DownloadThead.date)+"/"+ UUID.randomUUID()+".mp4"));

            InputStream inputStream = HttpUtil.createGet(url).execute().bodyStream();
            Integer total = FileUtils.getFileSize(url);
            byte []bytes=new byte[1024];
            int len=0;
            double currentPercentage = 0;
            while ((len=inputStream.read(bytes))!=-1){
                bufferedOutputStream.write(bytes,0,len);
                currentPercentage+=len;
                progress=Double.parseDouble(new DecimalFormat("0.0").format( currentPercentage/total));
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (bufferedOutputStream!=null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }




}
